public class CaseBlacklistController
{
    List<blacklistWrapper> blackList = new List<blacklistWrapper>();
    
    public String emailAddress {get; set;}
    public String message {get; set;}
    public String submitMessage {get; set;}
    
    public List<blacklistWrapper> getBlacklist()
    {
        blackList.clear();
        List<CaseBlackList__c> bl = CaseBlacklistHandler.getBlackList();
        for (CaseBlackList__c b : bl)
        {
            blackList.add(new blacklistWrapper(b));
        }
        return blackList;
    }
    
    public void setEmailString(String email)
    {
        emailAddress = email;        
    }
    public String getMessage()
    {
        return message;      
    }
    public String getSubmitMessage()
    {
        return submitMessage;      
    }
    
    public PageReference addEmail()
    {       
        Boolean valid = ValidateEmail(emailAddress);
        //system.debug(emailAddress);
        if (valid)
        {
            message = '';  
            CaseBlacklistHandler.add(emailAddress);   
        }
        else
        {
            message = 'invalid email';     
        }
        emailAddress = '';
        
        return null;   
    }
    
    public PageReference submitChanges()
    {
           
        message = '';
        for (blacklistWrapper w : blackList)
        {          
            if (isDirty(w))
            {
                CaseBlacklistHandler.edit(w.bl.Email__c, w.autoClose, w.noReply, w.enabled);
            }        
        }
  
        submitMessage = 'Changes submitted';  
        emailAddress = '';
        
        return null;   
    }
    
    public PageReference clearSubmit()
    {
        submitMessage = '';
        return null;
    }
    
    
    public Boolean ValidateEmail(string email)
    {
        String pat = '[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\*\\/\\=\\?\\^\\_\\+\\-\\`\\{\\|\\}\\~\'._%+-]+@[a-zA-Z0-9\\-.-]+\\.[a-zA-Z]+';
        Boolean test = Pattern.matches(pat, email);
        return test;
    }
    
    public Boolean isDirty(blacklistWrapper w)
    {
        if ((w.enabled == w.bl.Active__c) &&
            (w.noReply == w.bl.NoAutoreply__c) &&
            (w.autoClose == w.bl.AutoCloseCase__c))
        {
            return false;
        }
        else
        {
            return true;
        }
    }   
    
    
    public class blacklistWrapper
    {
        public CaseBlackList__c bl {get; set;}
        public Boolean enabled {get; set;}
        public Boolean noReply {get; set;}
        public Boolean autoClose {get; set;}
        public blacklistWrapper(CaseBlackList__c e)
        {
            bl = e;
            enabled = e.Active__c;
            noReply = e.NoAutoreply__c;
            autoClose = e.AutoCloseCase__c;
        }    
    }
}